const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { ProvidePlugin } = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { merge } = require("webpack-merge");
const devConfig = require("./webpack.dev");
const prodConfig = require("./webpack.prod");

const getCommonConfig = function (isProd) {
  console.log("🚀 ~ getCommonConfig ~ isProd:", isProd);
  return {
    entry: "./src/main.js",
    devtool: false,
    output: {
      filename: "js/[name]_[chunkhash:5]_bundle.js",
      path: path.resolve(__dirname, "./dist"),
      clean: true,
      chunkFilename: "js/[name]_[chunkhash:5]_chunk.js",
    },
    target: "web",
    resolve: {
      extensions: [".js", ".json", ".jsx", ".vue", ".ts"],
    },
    module: {
      rules: [
        {
          test: /\.m?jsx?$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
          },
        },
        {
          test: /\.ts$/,
          use: "babel-loader",
        },
        {
          test: /\.css$/,
          // 开发时使用style-loader, 生产时使用MiniCssExtractPlugin.loader
          use: [
            // // 'style-loader', //开发阶段
            // MiniCssExtractPlugin.loader, // 生产阶段
            isProd ? MiniCssExtractPlugin.loader : "style-loader",
            "css-loader",
          ],
        },
      ],
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: "./index.html",
        cache: true, // 缓存
        minify: isProd
          ? {
              // 移除注释
              removeComments: true,
              // 移除属性
              removeEmptyAttributes: true,
              // 移除默认属性
              removeRedundantAttributes: true,
              // 折叠空白字符
              collapseWhitespace: true,
              // 压缩内联的CSS
              minifyCSS: true,
              // 压缩JavaScript
              minifyJS: {
                mangle: {
                  toplevel: true,
                },
              },
            }
          : false,
      }),
      new ProvidePlugin({
        axios: ["axios", "default"],
        // get: ['axios', 'get'],
        dayjs: "dayjs",
      }),
    ],
  };
};

module.exports = function (env) {
  const isProd = env.production;
  let mergeConfig = isProd ? prodConfig : devConfig;
  const finalConfig = merge(getCommonConfig(isProd), mergeConfig);
  console.log("🚀 ~ finalConfig.plugins:", finalConfig.plugins);
  return finalConfig;
};
